<template>
    <div class="courses-section">
        <div class="section-header">
            <h2>课程管理</h2>
            <el-button type="primary" @click="handleCreate">📚 添加课程</el-button>
        </div>

        <div class="table-container">
            <el-table :data="courseList" v-loading="loading" style="width: 100%">
                <el-table-column prop="title" label="课程名称" min-width="200" />
                <el-table-column prop="author" label="作者" width="120" />
                <el-table-column prop="sort" label="排序" width="80" />
                <el-table-column prop="status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ getStatusText(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleView(row)">查看</el-button>
                        <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button v-if="userType === 'admin' && row.status === 'pending'" size="small" type="success"
                            @click="handleApprove(row)">
                            审核
                        </el-button>
                        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- View Course Details Dialog -->
        <el-dialog v-model="showDetailDialog" :title="detailTitle" width="800px">
            <div v-if="currentItem" class="detail-content">
                <div class="course-detail">
                    <h3>{{ currentItem.name }}</h3>
                    <div class="detail-info">
                        <p><strong>作者：</strong>{{ currentItem.author }}</p>
                        <p><strong>排序：</strong>{{ currentItem.sort }}</p>
                        <p><strong>创建时间：</strong>{{ currentItem.createTime }}</p>
                        <p><strong>状态：</strong>
                            <el-tag :type="getStatusType(currentItem.status)">
                                {{ getStatusText(currentItem.status) }}
                            </el-tag>
                        </p>
                    </div>
                    <div class="cover-section">
                        <h4>课程封面：</h4>
                        <div class="image-placeholder" style="height: 200px;">
                            课程封面展示区域
                        </div>
                    </div>
                    <div class="video-section">
                        <h4>课程视频：</h4>
                        <div class="image-placeholder" style="height: 300px;">
                            课程视频播放区域
                        </div>
                    </div>
                    <div class="summary-section">
                        <h4>课程简介：</h4>
                        <p>{{ currentItem.summary || '暂无课程简介' }}</p>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- Create/Edit Course Dialog -->
        <el-dialog v-model="showFormDialog" :title="isEditing ? '编辑课程' : '添加课程'" width="700px"
            @closed="resetCourseForm">
            <el-form :model="courseForm" :rules="courseRules" ref="courseFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-form-item label="课程名称" prop="title">
                            <el-input v-model="courseForm.title" placeholder="请输入课程名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="courseForm.sort" :min="1" :max="999" style="width: 100%"
                                placeholder="排序" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="作者" prop="author">
                    <el-input v-model="courseForm.author" placeholder="请输入作者姓名" />
                </el-form-item>

                <el-form-item label="课程封面">
                    <div class="upload-area">
                        <div class="image-placeholder" @click="handleImageUpload">
                            📚 点击上传课程封面
                            <p style="font-size: 12px; color: #999; margin-top: 5px;">
                                建议尺寸 400x300，支持 JPG、PNG 格式
                            </p>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="课程视频">
                    <div class="upload-area">
                        <div class="image-placeholder" style="height: 150px;" @click="handleVideoUpload">
                            🎥 点击上传课程视频
                            <p style="font-size: 12px; color: #999; margin-top: 5px;">
                                支持 MP4、AVI 格式，最大 500MB
                            </p>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="课程简介" prop="summary">
                    <el-input v-model="courseForm.summary" type="textarea" :rows="4" placeholder="请输入课程简介..." />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showFormDialog = false">取消</el-button>
                    <el-button type="primary" @click="saveCourse" :loading="submitLoading">
                        {{ isEditing ? '更新' : '添加' }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import courseApi from '@/api/course';

const userType = ref(localStorage.getItem('userType') || 'enterprise');
const loading = ref(true);
const submitLoading = ref(false);
const courseList = ref([]);
const courseFormRef = ref();
const showFormDialog = ref(false);
const showDetailDialog = ref(false);
const isEditing = ref(false);
const currentItem = ref(null);
const detailTitle = ref('');

const courseForm = ref({
    title: '',
    author: '',
    sort: 1,
    summary: '',
    cover: null,
    videoUrl: null
});

const courseRules = {
    title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
    author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
    summary: [{ required: true, message: '请输入课程简介', trigger: 'blur' }]
};

const getStatusText = (status) => {
    const texts = {
        pending: '待审核', 0: '待审核',
        approved: '已通过', pass: '已通过', 1: '已通过',
        rejected: '已拒绝', reject: '已拒绝', 2: '已拒绝'
    };
    return texts[status] || status;
};

const getStatusType = (status) => {
    const types = {
        pending: 'warning', 0: 'warning',
        approved: 'success', pass: 'success', 1: 'success',
        rejected: 'danger', reject: 'danger', 2: 'danger'
    };
    return types[status] || 'info';
};

const formatDateTime = (isoString) => {
    if (!isoString) return '';
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const fetchCourses = async () => {
    loading.value = true;
    try {
        const response = await courseApi.getCourseList();
        courseList.value = response.content || response;
    } catch (error) {
        ElMessage.error('获取课程列表失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
};

onMounted(fetchCourses);

const resetCourseForm = () => {
    isEditing.value = false;
    currentItem.value = null;
    courseForm.value = { title: '', author: '', sort: 1, summary: '', cover: null, videoUrl: null };
    if (courseFormRef.value) {
        courseFormRef.value.resetFields();
    }
};

const handleCreate = () => {
    resetCourseForm();
    isEditing.value = false;
    showFormDialog.value = true;
};

const handleEdit = (row) => {
    resetCourseForm();
    isEditing.value = true;
    currentItem.value = { ...row };
    courseForm.value = { ...row };
    showFormDialog.value = true;
};

const handleView = (row) => {
    currentItem.value = row;
    detailTitle.value = '课程详情';
    showDetailDialog.value = true;
};

const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除课程 "${row.title}" 吗？`, '确认删除', { type: 'warning' });
        
        const result = await courseApi.deleteCourse(row.id);

        // Manually check for backend error payload in a 2xx response
        if (result && (result.code !== undefined && result.code !== 0 && result.code !== 200) || (result && result.success === false)) {
            throw new Error(result.msg || result.message || '后端返回操作失败');
        }

        ElMessage.success('删除成功');
        await fetchCourses();
    } catch (error) {
        if (error !== 'cancel') {
            const errorMessage = error.response ? (error.response.data.message || error.response.data) : (error.message || '删除失败');
            ElMessage.error(typeof errorMessage === 'object' ? JSON.stringify(errorMessage) : errorMessage);
            console.error('删除课程时发生错误:', error.response ? error.response.data : error);
        }
    }
};

const handleApprove = async (row) => {
    try {
        await ElMessageBox.confirm('确定要审核通过这个课程吗？', '确认操作', { type: 'warning' });
        await courseApi.auditCourse(row.id, { status: 'pass' });
        ElMessage.success('课程审核通过');
        await fetchCourses();
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('审核操作失败');
        }
    }
};

const saveCourse = async () => {
    if (!courseFormRef.value) return;
    await courseFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true;
            try {
                if (isEditing.value) {
                    await courseApi.updateCourse(currentItem.value.id, courseForm.value);
                    ElMessage.success('课程更新成功');
                } else {
                    await courseApi.addCourse(courseForm.value);
                    ElMessage.success('课程添加成功');
                }
                showFormDialog.value = false;
                await fetchCourses();
            } catch (error) {
                ElMessage.error(isEditing.value ? '更新失败' : '添加失败');
            } finally {
                submitLoading.value = false;
            }
        }
    });
};

// Mock functions for upload, can be implemented later
const handleImageUpload = () => ElMessage.info('图片上传功能待实现');
const handleVideoUpload = () => ElMessage.info('视频上传功能待实现');

</script>

<style scoped>
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-header h2 {
    margin: 0;
    color: #333;
}

.table-container {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.upload-area {
    margin-top: 10px;
}

.image-placeholder {
    width: 100%;
    height: 120px;
    border: 2px dashed #ddd;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    color: #666;
}

.image-placeholder:hover {
    border-color: #409eff;
    color: #409eff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.detail-content h3 {
    margin-bottom: 20px;
    color: #333;
    border-bottom: 2px solid #f0f0f0;
    padding-bottom: 10px;
}

.detail-content h4 {
    margin: 20px 0 10px 0;
    color: #666;
}

.detail-info p {
    margin: 10px 0;
    color: #666;
}

.cover-section,
.video-section,
.summary-section {
    margin-bottom: 20px;
}
</style>